<?php

namespace app\api\controller;
use think\Lang;

/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 卖家商品控制器
 */
class Sellergoods extends MobileSeller
{
    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        Lang::load(APP_PATH . 'home/lang/'.config('default_lang').'/sellergoodsadd.lang.php');
    }


    /**
     * @api {POST} api/Sellergoods/goods_list 出售中的商品列表
     * @apiVersion 1.0.0
     * @apiGroup Sellergoods
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {String} keyword 关键词
     * @apiParam {String} goods_type 商品类型 lockup违规的商品 offline仓库的商品 waitverify等待审核的商品
     * @apiParam {Int} search_type 0商品名 1货号 2商品公共ID
     * @apiParam {String} page 页码
     * @apiParam {String} pagesize 每页显示数量
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Object[]} result.goods_list  商品列表
     * @apiSuccess {String} result.goods_list.goods_addtime  添加时间
     * @apiSuccess {String} result.goods_list.goods_commonid  商品公共ID
     * @apiSuccess {String} result.goods_list.goods_image  商品图片
     * @apiSuccess {String} result.goods_list.goods_lock  商品锁定 0未锁，1已锁
     * @apiSuccess {String} result.goods_list.goods_name  商品名称
     * @apiSuccess {String} result.goods_list.goods_price  商品价格
     * @apiSuccess {String} result.goods_list.goods_state  商品状态 0:下架 1:正常 10:违规（禁售）
     * @apiSuccess {String} result.goods_list.goods_storage_sum  商品库存
     * @apiSuccess {Int} result.page_total  总页数
     * @apiSuccess {Boolean} result.hasmore  是否有更多 true是false否
     */
    public function goods_list()
    {
        $keyword = input('post.keyword');
        $goods_type = input('post.goods_type');
        $search_type = input('post.search_type');

        $goods_model = model('goods');

        $condition = array();
        $condition['store_id'] = $this->store_info['store_id'];
        if (trim($keyword) != '') {
            switch ($search_type) {
                case 0:
                    $condition['goods_name'] = array('like', '%' . trim($keyword) . '%');
                    break;
                case 1:
                    $condition['goods_serial'] = array('like', '%' . trim($keyword) . '%');
                    break;
                case 2:
                    $condition['goods_commonid'] = intval($keyword);
                    break;
            }
        }

        $fields = 'goods_commonid,goods_name,goods_price,goods_addtime,goods_image,goods_state,goods_lock';
        switch ($goods_type) {
            // 违规的商品
            case 'lockup':
                $goods_list = $goods_model->getGoodsCommonLockUpList($condition, $fields, $this->pagesize);
                break;
            //仓库的商品
            case 'offline':
                $goods_list = $goods_model->getGoodsCommonOfflineList($condition, $fields, $this->pagesize);
                break;
            //等待审核的商品
            case 'waitverify':
                $goods_list = $goods_model->getGoodsCommonWaitVerifyList($condition);
                break;
            default:
                $goods_list = $goods_model->getGoodsCommonOnlineList($condition, $fields, $this->pagesize);
                break;
        }

        // 计算库存
        $storage_array = $goods_model->calculateStorage($goods_list);

        // 整理输出的数据格式
        foreach ($goods_list as $key => $value) {
            $goods_list[$key]['goods_storage_sum'] = $storage_array[$value['goods_commonid']]['sum'];
            $goods_list[$key]['goods_addtime'] = date('Y-m-d', $goods_list[$key]['goods_addtime']);
            $goods_list[$key]['goods_image'] = goods_cthumb($goods_list[$key]['goods_image']);
        }

        $result = array_merge(array('goods_list' => $goods_list), mobile_page($goods_model->page_info));
        ds_json_encode(10000, '',$result);
    }

    /**
     * @api {POST} api/Sellergoods/goods_show 商品上架
     * @apiVersion 1.0.0
     * @apiGroup Sellergoods
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} commonid 商品公共ID
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    public function goods_show()
    {
        if ($this->store_info['store_state'] != 1) {
            ds_json_encode(10001,lang('wait_administrator_review_goods'));
        }
        
        $commonid = input('param.commonid');
        if (!preg_match('/^[\d,]+$/i', $commonid)) {
            ds_json_encode(10001,lang('para_error'));
        }
        $commonid_array = explode(',', $commonid);
        if ($this->store_info['store_state'] != 1) {
            ds_json_encode(10001,lang('store_goods_index_goods_show_fail'));
        }
        $return = model('goods')->editProducesOnline(array('goods_commonid' => array('in', $commonid_array), 'store_id' => $this->store_info['store_id']));
        if ($return) {
            // 添加操作日志
            $this->recordSellerlog('商品上架，平台货号：' . $commonid);
            ds_json_encode(10000, '',1);
        } else {
            ds_json_encode(10001,lang('store_goods_index_goods_show_fail'));
        }
        
    }


    /**
     * @api {POST} api/Sellergoods/goods_unshow 商品下架
     * @apiVersion 1.0.0
     * @apiGroup Sellergoods
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} commonid 商品公共ID
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    public function goods_unshow()
    {
        //参考PC端代码
        $common_id = $this->checkRequestCommonId(input('param.commonid'));
        $commonid_array = explode(',', $common_id);
        $goods_model = model('goods');
        $where = array();
        $where['goods_commonid'] = array('in', $commonid_array);
        $where['store_id'] = $this->store_info['store_id'];
        $return = model('goods')->editProducesOffline($where);
        if ($return) {
            // 更新优惠套餐状态关闭
            $goods_list = $goods_model->getGoodsList($where, 'goods_id');
            if (!empty($goods_list)) {
                $goodsid_array = array();
                foreach ($goods_list as $val) {
                    $goodsid_array[] = $val['goods_id'];
                }
                model('pbundling')->editBundlingCloseByGoodsIds(array('goods_id' => array('in', $goodsid_array)));
            }
            // 添加操作日志
            $this->recordSellerlog('商品下架，平台货号：' . $common_id);
            ds_json_encode(10000, '',1);
        } else {
            ds_json_encode(10001,lang('store_goods_index_goods_unshow_fail'));
        }
    }
    /**
     * 验证commonid
     */
    private function checkRequestCommonId($common_ids) {
        if (!preg_match('/^[\d,]+$/i', $common_ids)) {
            ds_json_encode(10001,lang('para_error'));
        }
        return $common_ids;
    }
    
    /**
     * @api {POST} api/Sellergoods/goods_unshow 商品删除
     * @apiVersion 1.0.0
     * @apiGroup Sellergoods
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} commonid 商品公共ID
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    public function drop_goods()
    {
        $commonid = input('param.commonid');
        $common_id = $this->checkRequestCommonId($commonid);
        $commonid_array = explode(',', $common_id);

        $goods_model = model('goods');
        $where = array();
        $where['goods_commonid'] = array('in', $commonid_array);
        $where['store_id'] = $this->store_info['store_id'];
        $return = $goods_model->delGoodsNoLock($where);

        if ($return) {
            // 添加操作日志
            $this->recordSellerlog('删除商品，平台货号：' . $common_id);
            ds_json_encode(10000, '',1);
        } else {
            ds_json_encode(10001,lang('store_goods_index_goods_del_fail'));
        }
        
    }
}